package com.grass.cropTradingCenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grass.cropTradingCenter.common.OutputException;
import com.grass.cropTradingCenter.common.PageResult;
import com.grass.cropTradingCenter.mapper.AdminUserMapper;
import com.grass.cropTradingCenter.mapper.MiniShopMapper;
import com.grass.cropTradingCenter.pojo.dto.admin.HomeData;
import com.grass.cropTradingCenter.pojo.entity.*;
import com.grass.cropTradingCenter.pojo.po.QueryImage;
import com.grass.cropTradingCenter.pojo.vo.admin.AdminUserVo;
import com.grass.cropTradingCenter.pojo.vo.admin.CommitPageVo;
import com.grass.cropTradingCenter.pojo.vo.admin.ShopAuthListVo;
import com.grass.cropTradingCenter.pojo.vo.admin.UpdateAuthStateVo;
import com.grass.cropTradingCenter.pojo.vo.common.PageVo;
import com.grass.cropTradingCenter.pojo.vo.common.UpdateStateVo;
import com.grass.cropTradingCenter.pojo.vo.shop.GoodsListVo;
import com.grass.cropTradingCenter.pojo.vo.user.LoginVo;
import com.grass.cropTradingCenter.service.*;
import com.grass.cropTradingCenter.utils.SecurityUtils;
import com.grass.cropTradingCenter.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zipan
 * @description 针对表【admin_user】的数据库操作Service实现
 * @createDate 2024-01-23 19:41:54
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser>
        implements AdminUserService {

    @Autowired
    AdminUserMapper adminUserMapper;

    @Autowired
    ShopAuthService authService;

    @Autowired
    MiniShopUserServiceImpl shopUserService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    ImageService imageService;

    @Autowired
    GoodsPackageService goodsPackageService;

    @Autowired
    UserCommitService userCommitService;

    @Autowired
    UserOrderService userOrderService;

    @Autowired
    MiniUserService miniUserService;

    @Autowired
    MiniShopMapper miniShopMapper;

    @Override
    public String login(LoginVo vo) {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getAdminAccount, vo.getEmail())
                .eq(AdminUser::getAdminPassword, vo.getPassword());
        AdminUser user = this.getOne(queryWrapper);
        if (user == null) throw new OutputException("账号或密码错误");

        if (user.getForbiddenFlag() == 1) throw new OutputException("账号被封禁，请联系管理员");

        // 更新登录时间
        user.setLastLoginTime(user.getThisLoginTime());
        user.setThisLoginTime(new Date());
        this.updateById(user);

        return TokenUtil.getToken(user.getAdminId(), "admin");
    }

    @Override
    public AdminUser getUserInfo() {
        int userId = SecurityUtils.getAdminUserId();
        return this.getById(userId);
    }

    @Override
    public PageResult<AdminUser> getAdminList(PageVo vo) {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(AdminUser::getAdminId, SecurityUtils.getAdminUserId());
        if (!StringUtils.isBlank(vo.getKey())) {
            queryWrapper.and((wrapper) -> {
                wrapper.like(AdminUser::getPhone, vo.getKey())
                        .or().like(AdminUser::getRealName, vo.getKey())
                        .or().like(AdminUser::getAdminAccount, vo.getKey());
            });
        }
        Page<AdminUser> page = this.page(new Page<>(vo.getPageNum(), vo.getPageSize()), queryWrapper);
        return PageResult.ofPage(page);
    }

    @Override
    public void addOrUpdateAdmin(AdminUserVo vo) {
        AdminUser adminUser = new AdminUser();
        BeanUtils.copyProperties(vo, adminUser);
        // 如果是新增
        if(vo.getAdminId() == null || vo.getAdminId() == 0){
            // 查询有没有这个账户
            LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdminUser::getAdminAccount, vo.getAdminAccount());
            int count = this.count(queryWrapper);
            if(count >= 1) throw new OutputException("该账号已经存在");
            this.save(adminUser);
            return;
        }
        this.updateById(adminUser);
    }

    @Override
    public void deleteAdmin(AdminUserVo vo) {
        if(vo.getAdminId() == null || vo.getAdminId() == 0) throw new OutputException("该管理员不存在");
        this.removeById(vo.getAdminId());
    }

    @Override
    public PageResult<ShopAuth> shopAuthList(ShopAuthListVo vo) {
        LambdaQueryWrapper<ShopAuth> queryWrapper = new LambdaQueryWrapper<>();
        // 筛选符合的状态
        if(vo.getState() != 10){
            queryWrapper.eq(ShopAuth::getCheckFlag, vo.getState());
        }

        // 搜索条件
        if(!StringUtils.isBlank(vo.getKey())){
            queryWrapper.and((wrapper)->{
                wrapper.like(ShopAuth::getShopUserId, vo.getKey())
                        .or().like(ShopAuth::getRealName, vo.getKey())
                        .or().like(ShopAuth::getPhone, vo.getKey())
                        .or().like(ShopAuth::getIdCard, vo.getKey());
            });
        }

        Page<ShopAuth> page = authService.page(new Page<>(vo.getPageNum(), vo.getPageSize()), queryWrapper);
        return PageResult.ofPage(page);
    }

    @Override
    public void updateAuthState(UpdateAuthStateVo vo) {
        ShopAuth shopAuth = new ShopAuth();
        shopAuth.setAuthId(vo.getAuthId());
        shopAuth.setCheckFlag(vo.getCheckFlag());
        shopAuth.setPassTime(new Date());
        if(!StringUtils.isBlank(vo.getRemark())){
            shopAuth.setRemark(vo.getRemark());
        }
        authService.updateById(shopAuth);
        // 更新shopUserId的是否实名认证状态
        if(vo.getCheckFlag() == 1){
            MiniShopUser miniShopUser = new MiniShopUser();
            miniShopUser.setShopUserId(vo.getShopUserId());
            miniShopUser.setIsAuth(1);
            shopUserService.updateById(miniShopUser);
        }

    }

    @Override
    public void updateGoodsCheckFlag(UpdateStateVo vo) {
        Goods goods = new Goods();
        goods.setGoodsId(vo.getOtherId());
        goods.setCheckFlag(vo.getCheckFlag());
        goodsService.updateById(goods);
    }

    @Override
    public PageResult<Goods> goodsList(GoodsListVo vo) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNoneBlank(vo.getKey())){
            queryWrapper.and((wrapper)->{
                wrapper.like(Goods::getGoodsName, vo.getKey())
                        .or().like(Goods::getGoodsDescription, vo.getKey())
                        .or().like(Goods::getGoodsId, vo.getKey());
            });
        }
        if(vo.getState() != 10){
            queryWrapper.eq(Goods::getCheckFlag, vo.getState());
        }
        if(vo.getSellFlag() != 10){
            queryWrapper.eq(Goods::getSellFlag, vo.getSellFlag());
        }

        Page<Goods> page = goodsService.page(new Page<>(vo.getPageNum(), vo.getPageSize()), queryWrapper);


        page.getRecords().forEach(goods -> {
            goods.setDetailImages(imageService.getImageList(new QueryImage(goods.getGoodsId(), 1)));
            goods.setPackages(goodsPackageService.getPackageList(goods.getGoodsId()));
        });
        return PageResult.ofPage(page);
    }

    @Override
    public PageResult<UserCommit> commitList(CommitPageVo vo) {
        int adminUserId = SecurityUtils.getAdminUserId();

        LambdaQueryWrapper<UserCommit> queryWrapper = new LambdaQueryWrapper<>();
        if (vo.getState() != 10) {
            queryWrapper.eq(UserCommit::getCommitType, vo.getState());
        }
        if (StringUtils.isNotEmpty(vo.getKey())) {
            queryWrapper.and(wrapper -> {
                wrapper.like(UserCommit::getCommitText, vo.getKey());
            });
        }
        if (vo.getCommitRate() != 10) {
            queryWrapper.eq(UserCommit::getCommitRate, vo.getCommitRate());
        }

        queryWrapper.orderByDesc(UserCommit::getId);

        Page<UserCommit> page = userCommitService.page(new Page<>(vo.getPageNum(), vo.getPageSize()), queryWrapper);
        for (UserCommit commit : page.getRecords()) {
            commit.setOrder(userOrderService.getById(commit.getOrderId()));
            commit.setImageList(imageService.getImageList(new QueryImage(commit.getId(), 2)));
            commit.setUser(miniUserService.getById(commit.getUserId()));
        }
        return PageResult.ofPage(page);
    }

    @Override
    public void updateCommitCheckFlag(UpdateStateVo vo) {
        UserCommit userCommit = new UserCommit();
        userCommit.setId(vo.getOtherId());
        userCommit.setCommitType(vo.getCheckFlag());
        userCommitService.updateById(userCommit);
    }

    @Override
    public List<MiniShop> shopList() {
        List<MiniShop> shopList = miniShopMapper.getShopListFor8();
        for (MiniShop shop : shopList) {
            shop.setGoodsNum(goodsService.getGoodsNumByShopId(shop.getShopId()));
        }
        return shopList;
    }

    /**
     * 大屏数据
     *
     * @return
     */
    @Override
    public HomeData homeData() {
        // 成功单量
        HomeData homeData = new HomeData();
        homeData.setSuccessOrder(successOrder());
        homeData.setRefundOrder(refundOrder());
        homeData.setCommitNum(commitNum());
        homeData.setUserNum(userNum());
        homeData.setShopNum(shopNum());
        homeData.setCropNum(cropNum());
        return homeData;
    }

    private Integer cropNum() {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getCheckFlag, 1);
        return goodsService.count(queryWrapper);
    }

    private Integer shopNum() {

        return miniShopMapper.selectCount(new LambdaQueryWrapper<>());
    }

    private Integer commitNum() {
        return userCommitService.count();
    }

    private Integer userNum() {
        return miniUserService.count();
    }

    private Integer refundOrder() {
        LambdaQueryWrapper<UserOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or().eq(UserOrder::getOrderType, 10)
                .or().eq(UserOrder::getOrderType, 12);
        return userOrderService.count(queryWrapper);
    }

    // 成功单量
    private Integer successOrder() {
        LambdaQueryWrapper<UserOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or().eq(UserOrder::getOrderType, 4)
                .or().eq(UserOrder::getOrderType, 5);
        return userOrderService.count(queryWrapper);
    }
}




